package com.example.cash.craft.controller;

import com.example.cash.craft.pojo.core.CurrentPrincipal;
import com.example.cash.craft.pojo.param.UserRegisterParam;
import com.example.cash.craft.pojo.vo.PageData;
import com.example.cash.craft.pojo.vo.UserVO;
import com.example.cash.craft.service.IUserService;
import com.example.cash.craft.web.JsonResult;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

@Tag(name = "2. 用户管理模块")
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @ApiOperationSupport(order = 10)
    @Operation(summary = "[游客] 注册新用户")
    @PostMapping("/register")
    public JsonResult<Void> register(@ParameterObject @Valid UserRegisterParam param) {
        userService.register(param);
        return JsonResult.ok();
    }

    @ApiOperationSupport(order = 200)
    @Operation(summary = "[管理] 删除用户")
    @Parameter(name = "id", description = "用户id", required = true, example = "1")
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    @PostMapping("/{id}/delete")
    public JsonResult<Void> deleteById(@PathVariable Long id) {
        userService.deleteById(id);
        return JsonResult.ok();
    }

    @ApiOperationSupport(order = 410)
    @Operation(summary = "[用户] 查询个人信息")
    @GetMapping("/current")
    public JsonResult<UserVO> selectById(@AuthenticationPrincipal CurrentPrincipal principal) {
        UserVO data = userService.selectById(principal.getId());
        return JsonResult.ok(data);
    }

    @ApiOperationSupport(order = 410)
    @Operation(summary = "[管理] 根据ID查询用户信息")
    @Parameter(name = "id", description = "用户id", required = true, example = "1")
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    @GetMapping("/{id}")
    public JsonResult<UserVO> selectById(@PathVariable Long id) {
        UserVO data = userService.selectById(id);
        return JsonResult.ok(data);
    }

    @ApiOperationSupport(order = 420)
    @Operation(summary = "[管理] 查询所有用户列表")
    @Parameter(name = "page", description = "页码", example = "1", required = false)
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    @GetMapping()
    public JsonResult<PageData<UserVO>> listAll(Integer page) {
        if (page == null || page < 1) {
            page = 1;
        }
        PageData<UserVO> list = userService.listAll(page);
        return JsonResult.ok(list);
    }

}